package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.BoundsTo;
import com.atguigu.common.to.MemberPriceTo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.*;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeign;
import com.atguigu.gulimall.product.service.SpuInfoService;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescDao spuInfoDescDao;
    @Resource
    private SpuImagesDao spuImagesDao;
    @Resource
    private SkuInfoDao skuInfoDao;
    @Resource
    private SkuImagesDao skuImagesDao;
    @Resource
    private SkuSaleAttrValueDao skuSaleAttrValueDao;
    @Autowired
    private CouponFeign couponFeign;
    @Resource
    private ProductAttrValueDao productAttrValueDao;
    @Resource
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuInfoVo spuInfoVo) {
        // 1.保存基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        List<Baseattrs> baseattrs = spuInfoVo.getBaseAttrs();
        baseattrs.stream().map(baseattr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrValue(baseattr.getAttrValues());
            productAttrValueEntity.setAttrId(baseattr.getAttrId());
            AttrEntity attrEntity = attrDao.selectById(baseattr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setQuickShow(baseattr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueDao.insert(productAttrValueEntity);
            return productAttrValueEntity;
        });


        // 2.保存spu-info-desc信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",spuInfoVo.getImages()));
        spuInfoDescDao.insert(spuInfoDescEntity);

        // 3.保存spu-images
        List<String> images = spuInfoVo.getImages();
        List<SpuImagesEntity> spuImagesEntities = images.stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setImgUrl(image);
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            return spuImagesEntity;
        }).collect(Collectors.toList());
        for (SpuImagesEntity image: spuImagesEntities) {
            spuImagesDao.insert(image);
        }

        // 4.保存sku-info
        List<Skus> skus = spuInfoVo.getSkus();
        List<SkuInfoEntity> skuInfoEntities = skus.stream().map(sku -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
            skuInfoEntity.setBrandId(spuInfoVo.getBrandId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSkuDesc(String.join(",",sku.getDescar()));
            List<Images> images1 = sku.getImages();
            images1.forEach(images2 -> {
                if(images2.getDefaultImg() == 1) {
                    skuInfoEntity.setSkuDefaultImg(images2.getImgUrl());
                }
            });
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoDao.insert(skuInfoEntity);
            // 5.保存sku-images
//            for (Images images2: images1) {
//                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
//                BeanUtils.copyProperties(images2,skuImagesEntity);
//                skuImagesDao.insert(skuImagesEntity);
//            }
            List<SkuImagesEntity> imagesEntities = images1.stream().map(image -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                BeanUtils.copyProperties(image, skuImagesEntity);
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuImagesEntity;
            }).filter(skuImagesEntity -> {
                return skuImagesEntity.getDefaultImg() > 0;
            }).collect(Collectors.toList());
            for (SkuImagesEntity image: imagesEntities) {
                skuImagesDao.insert(image);
            }

            // 6.保存sku-sale-attr
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            for (SkuSaleAttrValueEntity skuSaleAttrValueEntity: skuSaleAttrValueEntities) {
                skuSaleAttrValueDao.insert(skuSaleAttrValueEntity);
            }

            // 7.保存sms-member-price/sms-ladderreduction/sms-fullreduction
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku,skuReductionTo);
            skuReductionTo.setSpuId(spuInfoEntity.getId());
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            List<Memberprice> memberprice = sku.getMemberPrice();
            List<MemberPriceTo> memberPriceTos = memberprice.stream().map(memberprice1 -> {
                MemberPriceTo memberPriceTo = new MemberPriceTo();
                memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                memberPriceTo.setMemberLevelId(memberprice1.getId());
                memberPriceTo.setMemberLevelName(memberprice1.getName());
                memberPriceTo.setMemberPrice(memberprice1.getPrice());
                memberPriceTo.setAddOther(memberprice1.getStatus());
                return memberPriceTo;
            }).collect(Collectors.toList());
            skuReductionTo.setMemberPriceTos(memberPriceTos);

            R r = couponFeign.saveSkuReduction(skuReductionTo);
            if (r.getCode() != 0) {
                log.error("远程保存memberPrice出错！");
            }

            return skuInfoEntity;
        }).collect(Collectors.toList());

        // 8.保存spu-bounds
        Bounds bounds = spuInfoVo.getBounds();
        BoundsTo boundsTo = new BoundsTo();
        BeanUtils.copyProperties(bounds,boundsTo);
        boundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeign.saveBounds(boundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存bounds出错！");
        }
    }

    /**
     page: 1,//当前页码
     limit: 10,//每页记录数
     sidx: 'id',//排序字段
     order: 'asc/desc',//排序方式
     key: '华为',//检索关键字
     catelogId: 6,//三级分类id
     brandId: 1,//品牌id
     status: 0,//商品状态
     */
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)) {
            wrapper.and(w -> {
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !catelogId.equals("0")) {
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !brandId.equals("0")) {
            wrapper.eq("brand_id",brandId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


}
